﻿using System.Threading;
using Microsoft.Phone.Notification;

namespace UpdateControls.Correspondence.POXClient
{
    public class ToastNotificationObserver
    {
        private IPOXConfigurationProvider _configurationProvider;
        private HttpNotificationChannel _httpChannel;
        private Dependent _depToastBound;

        public ToastNotificationObserver(IPOXConfigurationProvider configurationProvider)
        {
            _configurationProvider = configurationProvider;
            _depToastBound = new Dependent(UpdateToastBound);

            _depToastBound.Invalidated += () =>
                ThreadPool.QueueUserWorkItem(o =>
                    _depToastBound.OnGet());
            _depToastBound.OnGet();
        }

        #region Independent properties
        // Generated by Update Controls --------------------------------
        private Independent _indHttpChannel = new Independent();

        public HttpNotificationChannel HttpChannel
        {
            get { _indHttpChannel.OnGet(); return _httpChannel; }
            set { _indHttpChannel.OnSet(); _httpChannel = value; }
        }
        // End generated code --------------------------------
        #endregion

        private void UpdateToastBound()
        {
            HttpNotificationChannel httpChannel = HttpChannel;

            if (httpChannel != null)
            {
                if (_configurationProvider.IsToastEnabled)
                {
                    if (!httpChannel.IsShellToastBound)
                        httpChannel.BindToShellToast();
                }
                else
                {
                    if (httpChannel.IsShellToastBound)
                        httpChannel.UnbindToShellToast();
                }
            }
        }
    }
}
